<!-- eslint-disable vue/no-unused-vars -->
<!-- eslint-disable vue/no-duplicate-attributes -->
<!-- eslint-disable vue/valid-v-slot -->
<!-- eslint-disable vue/no-lone-template -->
<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader ref="tableHeaderRef" :show-filter="false">
          <template #search-content>
            <a-form ref="seachRef" :model="seachForm">
              <a-row :gutter="24">
                <a-col :span="4">
                  <a-form-item field="name" hide-label>
                    <a-input v-model="seachForm.name" placeholder="请输入模板名称" />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="addTime" hide-label>
                    <a-date-picker
                      class="width100"
                      v-model="seachForm.addTime"
                      show-time
                      :disabledDate="changeTraceEnd"
                      placeholder="请选择开始创建时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (seachForm.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (seachForm.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="endTime" hide-label>
                    <a-date-picker
                      class="width100"
                      v-model="seachForm.endTime"
                      show-time
                      :disabledDate="changeTraceStart"
                      placeholder="请选择结束创建时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (seachForm.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (seachForm.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="btns" hide-label>
                    <a-space :size="15">
                      <a-button
                        type="primary"
                        v-permission="bpsList"
                        html-type="submit"
                        @click="doRefresh(1)"
                        ><template #icon> <icon-search /> </template>搜索</a-button
                      >
                      <a-button v-permission="bpsList" @click="resetSeach"
                        ><template #icon>
                          <icon-sync theme="outline" size="14" />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>重置</template></a-button
                      >
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </TableHeader>
      </template>
      <template #table-config>
        <a-space :size="15">
          <a-button
            type="primary"
            v-permission="bpsAdd"
            html-type="submit"
            @click="modal.payVisible = true"
            >新建</a-button
          >
          <a-button
            v-permission="sharing"
            type="outline"
            status="warning"
            html-type="submit"
            @click="opens"
            >模板分润</a-button
          >
          <a-button
            v-permission="batchSharing"
            type="outline"
            status="warning"
            html-type="submit"
            @click="open"
            >固定分润</a-button
          >
        </a-space>
        <a-space :size="15">
          <TableConfig
            @update-border="onUpdateBorder"
            @update-striped="onUpdateStriped"
            @refresh="doRefresh"
          />
        </a-space>
      </template>
      <template #default>
        <a-table
          :bordered="{ wrapper: true, cell: tables.bordered }"
          :stripe="(tables.striped as boolean)"
          :loading="tables.tableLoading"
          :data="table.dataList"
          :pagination="false"
          :column-resizable="true"
          :rowKey="rowKey"
          :columns="tableColumns.list"
          table-layout-fixed
          hide-expand-button-on-empty
          :default-expand-all-rows="true"
          :scroll="{ x: 1500 }"
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumns.list"
              :key="item.key"
              :align="item.align"
              :title="(item.title as string)"
              :width="item.width"
              :data-index="(item.key as string)"
              :fixed="item.fixed"
              :ellipsis="true"
              :tooltip="true"
            >
              <template v-if="item.key === 'num'" #cell="{ record }">
                {{ record.templateRules.length }}
              </template>
              <template v-if="item.key === 'remarks'" #cell="{ record }">
                <span v-if="record.remarks">{{ record.remarks }}</span>
                <span v-else>---</span>
              </template>
              <template v-if="item.key === 'actions'" #cell="{ record }">
                <a-space>
                  <a-button
                    size="small"
                    v-permission="bpsUpdate"
                    type="text"
                    class="butten"
                    @click="payEdit(record)"
                  >
                    编辑
                  </a-button>
                  <a-button
                    size="small"
                    v-permission="bpsAdd"
                    type="text"
                    class="butten"
                    @click="copyEdit(record)"
                  >
                    复制
                  </a-button>
                  <a-button
                    size="small"
                    v-permission="bpsRule"
                    type="text"
                    class="butten"
                    @click="showfenrun(record)"
                  >
                    设置
                  </a-button>
                  <a-button
                    size="small"
                    v-permission="bpsDelete"
                    class="butten"
                    type="text"
                    @click="payDelete(record.id)"
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
      <!-- <template #footer>
        <TableFooter ref="tableFooterRef" :pagination="pagination" />
      </template> -->
    </TableBody>
    <!-- 编辑模板 -->
    <a-modal
      v-model:visible="modal.payVisible"
      width="650px"
      :mask-closable="false"
      @before-close="payClose"
    >
      <template #title> 编辑模板 </template>
      <a-form ref="payRef" :auto-label-width="true" :model="payForm">
        <a-form-item
          label="模板名称"
          field="name"
          asterisk-position="end"
          :rules="[
            { required: true, message: '请输入模板名称' },
            { minLength: 1, maxLength: 20, message: '长度在 1 - 20个字符' },
          ]"
        >
          <a-input placeholder="请输入模板名称" v-model.trim="payForm.name" />
        </a-form-item>
        <a-form-item label="备注" field="remarks">
          <a-input placeholder="请输入备注" v-model.trim="payForm.remarks" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="payClose">取消</a-button>
          <a-button type="primary" @click="okPay">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <!-- 模板分润 -->
    <a-modal
      v-model:visible="cardsVisibles"
      @before-close="beforeCloses"
      title="模板分润"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="sharingRef" :auto-label-width="true" :model="tForm">
        <a-form-item
          label="分润客户"
          asterisk-position="end"
          :rules="[{ required: true, message: '请选择分润客户' }]"
          :validate-trigger="['change']"
          field="userId"
        >
          <a-select
            allow-search
            v-model="tForm.userId"
            placeholder="请选择分润客户"
            :options="userList"
            :virtual-list-props="{ height: 200 }"
          />
        </a-form-item>
        <a-form-item
          label="分润模板"
          asterisk-position="end"
          :rules="[{ required: true, message: '请选择分润模板' }]"
          :validate-trigger="['change']"
          field="id"
        >
          <a-select allow-search v-model="tForm.id" placeholder="请选择分润模板">
            <a-option v-for="item in templateList" :key="item.id" :value="item.id">{{
              item.name
            }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="替换分润" field="cover">
          <a-select v-model="tForm.cover" placeholder="请选择是否替换分润">
            <a-option :value="1">已分润套餐重新分润</a-option>
            <a-option :value="0">已分润套餐不重新分润</a-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="beforeCloses">取消</a-button>
          <a-button type="primary" @click="setSharing">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <!-- 固定分润 -->
    <a-modal
      v-model:visible="cardsVisible"
      @before-close="cardClose"
      title="固定分润"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="bpsRef" :auto-label-width="true" :model="bpsForm">
        <!-- <a-form-item label="分润操作" field="close">
          <a-radio-group class="radio-bcg" v-model="bpsForm.type">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">进行分润</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">回收分润</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item> -->
        <a-form-item
          label="分润客户"
          asterisk-position="end"
          :rules="[{ required: true, message: '请选择分润客户' }]"
          :validate-trigger="['change']"
          field="userId"
        >
          <a-select
            v-model="bpsForm.userId"
            allow-search
            placeholder="请选择分润客户"
            :options="userList"
            :virtual-list-props="{ height: 200 }"
          />
        </a-form-item>
        <a-form-item
          label="分润系列"
          asterisk-position="end"
          :rules="[{ required: true, message: '请选择分润系列' }]"
          :validate-trigger="['change']"
          field="seriesId"
        >
          <a-select v-model="bpsForm.seriesId" allow-search placeholder="请选择分润系列">
            <a-option v-for="item in merchantTypeList" :key="item.id" :value="item.id">{{
              item.name
            }}</a-option>
          </a-select>
        </a-form-item>
        <div v-if="bpsForm.type == true">
          <!-- <a-form-item label="分润方案" field="userId">
            <a-select v-model="bpsForm.f" placeholder="请选择分润方案">
              <a-option :value="0">成本分润</a-option>
              <a-option :value="1">个性分润</a-option>
            </a-select>
          </a-form-item> -->
          <a-form-item label="替换分润" field="cover">
            <a-select v-model="bpsForm.cover" placeholder="请选择替换分润">
              <a-option :value="1">已分润套餐重新分润</a-option>
              <a-option :value="0">已分润套餐不重新分润</a-option>
            </a-select>
          </a-form-item>
          <!-- <a-form-item label="分润方式" v-if="bpsForm.t == 1" field="userId">
            <a-select v-model="bpsForm.s" placeholder="请选择分润方式">
              <a-option :value="0">系统成本+金额=客户成本</a-option>
              <a-option :value="1">系统售价-金额=客户成本</a-option>
            </a-select>
          </a-form-item> -->
          <a-form-item
            label="分润比例"
            field="proportion"
            asterisk-position="end"
            :rules="[{ required: true, message: '请输入分润比例' }]"
            :validate-trigger="['input']"
          >
            <a-input placeholder="请输入分润比例" v-model.trim="bpsForm.proportion" />
          </a-form-item>
        </div>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="cardClose">取消</a-button>
          <a-button type="primary" @click="setBatchSharing">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <!-- 编辑分润 -->
    <a-modal
      v-model:visible="updateFenrunisible"
      @before-close="handleCancelUpdateFenrun"
      title="编辑分润"
      width="500px"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="updateFenrunForms" :auto-label-width="true" :model="fenrunUpdateForm">
        <a-form-item
          field="cost"
          label="客户成本"
          asterisk-position="end"
          :rules="[{ required: true, message: '客户成本不能为空' }]"
          :validate-trigger="['change', 'input']"
        >
          <a-input-number
            v-model="fenrunUpdateForm.cost"
            placeholder="请输入客户成本"
            allow-clear
          />
        </a-form-item>
        <a-form-item
          field="price"
          label="客户售价"
          asterisk-position="end"
          :rules="[{ required: true, message: '客户售价不能为空' }]"
        >
          <a-input-number
            v-model="fenrunUpdateForm.price"
            :precision="2"
            placeholder="请输入客户售价"
            allow-clear
          />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="handleCancelUpdateFenrun">取消</a-button>
          <a-button type="primary" @click="submitUpdateFenrun">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <!-- 添加规则 -->
    <a-modal
      v-model:visible="roleV"
      @before-close="roleClose"
      title="批量分润"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="roleRef" :auto-label-width="true" :model="roleForm">
        <a-form-item label="所属渠道" field="channelIds">
          <a-select
            v-model="roleForm.channelIds"
            multiple
            :max-tag-count="1"
            placeholder="所属渠道"
            @change="changeCh"
          >
            <a-option v-for="item in channel" :key="item.id" :value="item.id">{{
              item.name
            }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属系列" field="seriesIds">
          <a-select
            v-model="roleForm.seriesIds"
            multiple
            :max-tag-count="1"
            placeholder="请选择所属系列"
            @change="changeSer"
          >
            <a-option v-for="item in list1" :key="item.id" :value="item.id">{{
              item.name
            }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属套餐" field="mealIds">
          <a-select
            v-model="roleForm.mealIds"
            multiple
            :max-tag-count="1"
            placeholder="请选择所属套餐"
          >
            <a-option v-for="item in list2" :key="item.id" :value="item.id">{{
              item.name
            }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="分润比例"
          field="proportion"
          asterisk-position="end"
          :rules="[{ required: true, message: '请输入分润比例' }]"
        >
          <a-input placeholder="请输入分润比例" v-model.trim="roleForm.proportion" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="roleClose">取消</a-button>
          <a-button type="primary" @click="roleOk">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <!-- 分润 -->
    <a-modal
      v-model:visible="fenrunvisible"
      @before-close=";(fenrunvisible = false), (loadingButton = false), (fuzhufenrunlist = [])"
      title="客户分润"
      width="880px"
      :footer="false"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="serchForm2" :model="fenrunForm" :style="{ width: '100%', marginBottom: '0px' }">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item field="channelId" hide-label>
              <a-select
                v-model="fenrunForm.channelId"
                allow-search
                placeholder="请选择渠道"
                allow-clear
              >
                <a-option v-for="item in channel" :key="item.id" :value="item.id">{{
                  item.name
                }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="seriesId" hide-label>
              <a-select
                v-model="fenrunForm.seriesId"
                allow-search
                placeholder="请选择系列"
                allow-clear
              >
                <a-option v-for="item in merchantTypeList" :key="item.id" :value="item.id">{{
                  item.name
                }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="setMealId" hide-label>
              <a-select
                v-model="fenrunForm.setMealId"
                allow-search
                placeholder="请选择套餐"
                allow-clear
              >
                <a-option v-for="item in mealList" :key="item.id" :value="item.id">{{
                  item.name
                }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="setMealType" hide-label>
              <a-select v-model="fenrunForm.setMealType" placeholder="请选择套餐类型" allow-clear>
                <a-option value="0">无限叠加</a-option>
                <a-option value="1">基础套餐</a-option>
                <a-option value="2">叠加包</a-option>
                <!-- <a-option value="3">体验包</a-option> -->
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div style="display: flex; justify-content: space-between; margin-bottom: 20px">
        <div style="width: 100%; display: flex; justify-content: space-between">
          <div></div>
          <div style="display: flex; align-items: center">
            <a-button type="primary" v-permission="bpsRuleSet" @click="addOpen">新建</a-button>
            <a-dropdown :popup-max-height="false" trigger="hover">
              <a-button style="margin-left: 12px">更多操作</a-button>
              <template #content>
                <a-doption @click="exportLists" v-permission="bpsRules">导出</a-doption>
                <a-doption @click="getLists" v-permission="getFenrunReset">删除</a-doption>
              </template>
            </a-dropdown>
          </div>
          <!-- <div>
            <a-input-number
              hide-button
              :style="{ width: '320px' }"
              v-model="type0Num"
              placeholder="请输入分润比例"
              allow-clear
            >
              <template #append>
                <a-button type="primary" status="success" @click="fuzhuClick">辅助计算</a-button>
              </template>
            </a-input-number>
            <a-button
              type="primary"
              style="margin-left: 12px"
              v-permission="bpsRuleUpdate"
              :loading="loadingButton"
              @click="submitFenrunList(0)"
              >确认分润</a-button
            >
          </div> -->
        </div></div
      >
      <a-spin :loading="classLoading" tip="加载中····" style="width: 100%">
        <a-table
          :bordered="{ wrapper: true, cell: tables.bordered }"
          :stripe="(tables.striped as boolean)"
          :row-class-name="rowClassNameFun"
          :data="table2.dataList"
          :pagination="false"
          :column-resizable="true"
          :rowKey="rowKey"
          table-layout-fixed
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumnsfenrunList.list"
              :key="item.key"
              :align="(item.align as any)"
              :title="(item.title as string)"
              :data-index="(item.key as string)"
              :width="item.width"
              :ellipsis="true"
              :tooltip="true"
            >
              <template v-if="item.key === 'actions'" #cell="{ record }">
                <a-space :size="2">
                  <a-button
                    style="margin-right: 5px; padding: 0px"
                    type="text"
                    size="small"
                    :key="record"
                    v-permission="bpsRuleUpdate"
                    @click="showUpdateFenrun(record)"
                    >编辑</a-button
                  >
                  <a-button
                    style="margin-right: 5px; padding: 0px"
                    type="text"
                    size="small"
                    status="warning"
                    v-permission="bpsRuleDelete"
                    @click="resetFenrun(record)"
                    >删除</a-button
                  >
                </a-space>
              </template>
              <template v-else-if="item.key === 'usercost'" #cell="{ record }">
                <span v-if="record.setMeal">
                  <!-- {{ record.setMeal.cost }}元 -->
                  <a-input-number
                    hide-button
                    @focus="inputgetRecord(record)"
                    @blur="inputSubmit(record)"
                    :style="{ background: 'none' }"
                    style="display: flex; justify-content: center"
                    v-model="record.setMeal.cost"
                  />
                </span>
                <span v-else>未分润</span>
              </template>
              <template v-else-if="item.key === 'userprice'" #cell="{ record }">
                <span v-if="record.setMeal">
                  <a-input-number
                    hide-button
                    @focus="inputgetRecord(record)"
                    @blur="inputSubmit(record)"
                    :style="{ background: 'none' }"
                    style="display: flex; justify-content: center"
                    v-model="record.setMeal.price"
                  />
                </span>
                <span v-else>未分润</span>
              </template>
              <template v-else-if="item.key === 'price'" #cell="{ record }">
                <span>{{ record.price }}</span>
              </template>
              <template v-else-if="item.key === 'name'" #cell="{ record }">
                <span>{{ record.setMeal.name }}</span>
              </template>
              <template v-else-if="item.key === 'cost'" #cell="{ record }">
                <span>{{ record.cost }}</span>
              </template>
            </a-table-column>
          </template>
        </a-table>
        <TableFooter :pagination="pagination2" position="center" />
      </a-spin>
      <template #footer>
        <!-- <a-button @click="handleCancelEdit">取消</a-button>
          <a-button type="primary" @click="handleBeforeOkEdit">确定</a-button> -->
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import {
    bpsList,
    bpsAdd,
    bpsUpdate,
    bpsDelete,
    getFenrunReset,
    bpsRule,
    bpsRuleSet,
    bpsRuleDelete,
    bpsRuleUpdate,
    bpsRules,
    sharing,
    templateMeal,
    batchSharing,
  } from '@/api/url'
  import useCommonStore from '@/store/modules/common'
  import { post, get } from '@/api/http'
  import { usePagination, useRowKey, useTable } from '@/hooks/table'
  import { onMounted, reactive, ref, watch } from 'vue'
  import { Message, Modal } from '@arco-design/web-vue'
  const updateFenrunisible = ref(false)
  const fenrunUpdateForm: any = ref({
    setMealId: '', //套餐ID
    cost: '', //套餐成本
    price: '', //套餐售价
  })
  const templateList: any = ref([])
  const cardsVisibles = ref(false)
  const table = useTable()
  const bpsRef = ref()
  const pagination = usePagination(doRefresh)
  const bpsForm = ref({
    type: true,
    userId: '', // 用户ID
    seriesId: '', // 系列ID
    proportion: '', // 分润比例
    cover: 1, // 是否覆盖
  })
  const tForm = ref({
    id: '', // 套餐分润模板ID
    userId: '', //  客户ID
    cover: 1, //  是否覆盖， true覆盖 false不覆盖
  })
  const roleForm = ref({
    setMealUserTemplateId: '',
    proportion: '',
    mealIds: [],
    channelIds: [],
    seriesIds: [],
  })
  const seachRef = ref()
  const payRef = ref()
  const loading = ref(false)
  const useCommon = useCommonStore()
  const rowKey = useRowKey('id')
  const cardsVisible = ref(false)
  const userList: any = ref([])

  const modal = ref({
    visible: false,
    templatesVisible: false,
    payVisible: false,
    paySystemVisible: false,
    randomVisible: false,
    num: 0,
    path: 0,
    moda: 0,
  })

  const payForm: any = ref({
    name: '', //模板名称
    remarks: '',
  })

  const seachForm: any = reactive({
    name: '',
    addTime: '',
    endTime: '',
  })

  const tables = reactive({
    tableLoading: false,
    bordered: false,
    striped: false,
  })

  const merchantTypeList: any = ref([])

  const tableColumns: any = reactive({
    list: [
      {
        title: '模板名称',
        key: 'name',
        dataIndex: 'name',
        align: 'left',
        checked: true,
      },
      {
        title: '套餐数量',
        key: 'num',
        dataIndex: 'num',
        align: 'left',
        checked: true,
        width: 270,
      },
      {
        title: '模板备注',
        key: 'remarks',
        dataIndex: 'remarks',
        align: 'left',
        checked: true,
        width: 270,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        align: 'left',
        checked: true,
        width: 190,
      },
      {
        title: '变动时间',
        key: 'createTime',
        dataIndex: 'createTime',
        align: 'left',
        checked: true,
        width: 190,
      },
      {
        title: '操作',
        key: 'actions',
        dataIndex: 'actions',
        align: 'left',
        checked: true,
        width: 270,
        fixed: 'right',
      },
    ],
    templateList: [
      {
        title: '模板名称',
        key: 'name',
        dataIndex: 'name',
        align: 'left',
        checked: true,
      },
      {
        title: '支付渠道',
        key: 'merchantName',
        dataIndex: 'merchantName',
        align: 'left',
        checked: true,
      },
      {
        title: '支付商户号',
        key: 'payTemplate',
        dataIndex: 'payTemplate',
        align: 'left',
        checked: true,
      },
      {
        title: '收款总金额',
        key: 'accumulation',
        dataIndex: 'accumulation',
        align: 'left',
        checked: true,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        align: 'left',
        checked: true,
      },
      {
        title: '操作',
        key: 'actions',
        dataIndex: 'actions',
        align: 'left',
        checked: true,
        width: 220,
        fixed: 'right',
      },
    ],
    paySystem: [
      {
        title: '支付方式',
        key: 'type',
        dataIndex: 'type',
        align: 'left',
        checked: true,
      },
      {
        title: '默认支付',
        key: 'select',
        dataIndex: 'select',
        align: 'left',
        checked: true,
      },
      {
        title: '支付推荐',
        key: 'recommend',
        dataIndex: 'recommend',
        align: 'left',
        checked: true,
      },
    ],
  })
  const fenrunForm: any = reactive({
    channelId: '',
    seriesId: '',
    setMealType: '',
    setMealId: '',
    setMealUserTemplateId: '',
  })

  const getTemplateMeal = () => {
    get({
      url: templateMeal,
      data: {},
    })
      .then((res) => {
        if (res.code == 0) {
          templateList.value = res.data
        }
      })
      .catch()
  }

  const opens = async () => {
    await userFn()
    await getTemplateMeal()
    await seriess()
    cardsVisibles.value = true
  }

  const beforeCloses = () => {
    sharingRef.value.resetFields()
    cardsVisibles.value = false
  }

  const sharingRef = ref()

  const setSharing = () => {
    sharingRef.value?.validate().then((error: any) => {
      if (!error) {
        get({
          url: sharing,
          data: {
            ...tForm.value,
          },
        })
          .then((res) => {
            if (res.code == 0) {
              Message.success(res.msg)
              beforeCloses()
            } else {
              Message.error(res.msg)
            }
          })
          .catch()
      }
    })
  }

  const open = async () => {
    await userFn()
    await seriess()
    cardsVisible.value = true
  }
  const setBatchSharing = () => {
    bpsRef.value?.validate().then((error: any) => {
      if (!error) {
        if (bpsForm.value.type == true) {
          get({
            url: batchSharing,
            data: {
              ...bpsForm.value,
            },
          })
            .then((res) => {
              if (res.code == 0) {
                Message.success(res.msg)
                cardClose()
              } else {
                Message.error(res.msg)
              }
            })
            .catch()
        }
      }
    })
  }
  const tableColumnsfenrunList = reactive({
    list: [
      {
        title: '套餐名称',
        key: 'name',
        dataIndex: 'name',
        checked: true,
        align: 'left',
      },
      {
        title: '系统成本',
        key: 'usercost',
        dataIndex: 'usercost',
        checked: true,
        width: 90,
        align: 'left',
      },
      {
        title: '系统售价',
        key: 'userprice',
        dataIndex: 'userprice',
        checked: true,
        width: 90,
        align: 'left',
      },
      {
        title: '客户成本',
        key: 'cost',
        dataIndex: 'cost',
        checked: true,
        width: 90,
        align: 'left',
      },
      {
        title: '客户售价',
        key: 'price',
        dataIndex: 'price',
        checked: true,
        width: 90,
        align: 'left',
      },

      {
        title: '操作',
        key: 'actions',
        dataIndex: 'actions',
        checked: true,
        width: 120,
        align: 'left',
      },
    ],
  })
  const list1: any = ref([])
  const list2: any = ref([])
  const changeCh = () => {
    useCommon.seriess(roleForm.value.channelIds.join(',')).then((res) => {
      list1.value = res.data
    })
  }
  const changeSer = () => {
    useCommon.mealListFn(roleForm.value.seriesIds.join(',')).then((res) => {
      list2.value = res.data
    })
  }
  const roleRef = ref()
  const roleClose = () => {
    roleRef.value.resetFields()
    roleV.value = false
  }

  const roleOk = () => {
    roleRef.value?.validate().then((error: any) => {
      if (!error) {
        post({
          url:
            bpsRuleSet +
            '?setMealUserTemplateId=' +
            fenrunForm.setMealUserTemplateId +
            '&proportion=' +
            roleForm.value.proportion,
          data: roleForm.value.mealIds,
        })
          .then((res) => {
            if (res.code == 0) {
              Message.success(res.msg)
              getFenruns()
              roleClose()
            } else {
              Message.error(res.msg)
            }
          })
          .catch()
      }
    })
  }
  const roleV = ref(false)
  const addOpen = () => {
    roleV.value = true
  }
  function showUpdateFenrun(item: any) {
    fenrunUpdateForm.value = {
      setMealId: item.setMealId, //套餐ID
      cost: item.cost, //套餐成本
      price: item.price, //套餐售价
    }
    updateFenrunisible.value = true
  }
  function resetFenrun(item: any) {
    console.log(item)
    Modal.warning({
      title: '操作确认',
      content: '确定删除此条分润吗？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '删除',
      onOk: () => {
        get({
          url: bpsRuleDelete,
          data: {
            setMealUserTemplateId: fenrunForm.setMealUserTemplateId,
            setMealId: item.setMealId,
          },
        })
          .then((res) => {
            if (res.code == 0) {
              Message.success(res.msg)
              getFenruns()
            } else {
              Message.error(res.msg)
            }
          })
          .catch()
      },
    })
  }
  function rowClassNameFun(_record: any, index: number) {
    return index % 2 === 1 && table.striped.value ? 'table-striped' : null
  }
  const checkFenrunType: any = ref(0)
  const updateFenrunForms = ref()
  const handleCancelUpdateFenrun = () => {
    updateFenrunForms.value?.resetFields()
    updateFenrunisible.value = false
  }
  const submitUpdateFenrun = () => {
    updateFenrunForms.value?.validate().then((error: any) => {
      if (!error) {
        let a = []
        a.push(fenrunUpdateForm.value)
        fenrunSubmit(a)
      } else {
      }
    })
  }
  const fenrunSubmit = (item: any) => {
    if (item.length <= 0) {
      return false
    }
    post({
      url: bpsRuleUpdate,
      data: {
        setMealUserTemplateId: fenrunForm.setMealUserTemplateId,
        ...fenrunUpdateForm.value,
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        updateFenrunisible.value = false
        updateFenrunForms.value?.resetFields()
        getFenruns()
      }
    })
  }
  const pagination2 = usePagination(getFenruns)
  const classLoading = ref(false)
  const table2: any = reactive({
    dataList: [],
  })
  function changeType() {
    fuzhufenrunlist.value = []
    type0Num.value = 0
  }
  const fenrunvisible = ref(false)
  const fuzhufenrunlist: any = ref([])
  const type0Num: any = ref(0)

  function showfenrun(item: any) {
    fenrunForm.setMealUserTemplateId = item.id
    fuzhufenrunlist.value = []
    type0Num.value = 0
    fenrunvisible.value = true
  }
  // 监听对象
  watch(
    () => fenrunForm,
    () => {
      getFenruns(1)
    },
    {
      deep: true, // 深度监听的参数
    }
  )

  function getFenruns(value?: any) {
    classLoading.value = true
    if (value) {
      pagination2.page = value
    }
    get({
      url: bpsRule,
      data: {
        page: pagination2.page,
        size: pagination2.pageSize,
        ...fenrunForm,
      },
    })
      .then((res) => {
        classLoading.value = false
        table2.dataList = res.data.list
        pagination2.setTotalSize((res.data as any).totalSize)
      })
      .catch()
  }
  function getLists() {
    get({
      url: getFenrunReset,
      data: {
        userId: fenrunForm.userId,
      },
    })
      .then((res) => {
        if (res.code == 0) {
          Message.success(res.message)
          getFenruns(1)
        }
      })
      .catch()
  }
  const loadingButton = ref(false)
  function submitFenrunList(index: number) {
    // Message.error('此功能正在开发中')
    loadingButton.value = true
    post({
      url: bpsRuleUpdate,
      data: {
        ...fuzhufenrunlist.value[index],
      },
    })
      .then((res) => {
        const number = index + 1
        if (res.code == 0) {
          if (number < fuzhufenrunlist.value.length) {
            submitFenrunList(number)
          } else {
            Message.success(res.msg)
            loadingButton.value = false
            getFenruns()
          }
        }
      })
      .catch((res) => {
        const number = index + 1
        if (number < fuzhufenrunlist.value.length) {
          submitFenrunList(number)
        } else {
          Message.success(res.msg)
          loadingButton.value = false
          getFenruns()
        }
      })
  }
  function fuzhuClick() {
    fuzhufenrunlist.value = []
    table2.dataList.forEach((item1: any) => {
      item1.cost = Number(
        (item1.price - Math.floor(item1.price * (type0Num.value / 100) * 100) / 100).toFixed(2)
      ) //套餐成本
      item1.price = item1.price //套餐售价

      fuzhufenrunlist.value.push({
        setMealId: item1.setMealId, //套餐ID
        cost: item1.cost,
        price: item1.price, //套餐售价
        close: false, //状态true关闭,  false正常
        setMealUserTemplateId: item1.setMealUserTemplateId,
      })
    })
    // setTimeout(() => {

    // }, 1000);
  }

  const cardClose = () => {
    bpsRef.value.resetFields()
    cardsVisible.value = false
  }

  function userFn() {
    useCommon.userLists().then((res) => {
      userList.value = res.data
    })
  }

  const exportLists = () => {
    useCommon
      .downLoad(bpsRules, fenrunForm, '模板分润列表')
      .then(() => {})
      .catch(() => {})
  }

  const copyEdit = (val: any) => {
    Modal.warning({
      title: '操作确认',
      content: '确定要复制此模板？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '确定',
      onOk() {
        post({
          url: bpsAdd,
          data: {
            ...val,
          },
        }).then((res) => {
          if (res.code == 0) {
            Message.success(res.msg)
            doRefresh()
          }
        })
      },
    })
  }

  const payDelete = (val: number) => {
    Modal.warning({
      title: '操作确认',
      content: '确定要删除此模板？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '确定',
      onOk() {
        get({
          url: bpsDelete,
          data: {
            id: val,
          },
        }).then((res) => {
          if (res.code == 0) {
            Message.success(res.msg)
            doRefresh()
          }
        })
      },
    })
  }

  const payEdit = (val: any) => {
    payForm.value = JSON.parse(JSON.stringify(val))
    modal.value.payVisible = true
  }

  const payClose = () => {
    payForm.value.id = null
    payRef.value.resetFields()
    modal.value.payVisible = false
  }

  const okPay = () => {
    payRef.value.validate((error: any) => {
      if (!error) {
        if (payForm.value.id) {
          updatePays()
        } else {
          addPays(payForm.value)
        }
      }
    })
  }

  const addPays = (val: any) => {
    post({
      url: bpsAdd,
      data: {
        ...val,
      },
    }).then((res: any) => {
      if (res.code == 0) {
        Message.success(res.msg)
        payClose()
        doRefresh()
      }
    })
  }

  const updatePays = () => {
    post({
      url: bpsUpdate,
      data: {
        ...payForm.value,
      },
    }).then((res: any) => {
      if (res.code == 0) {
        Message.success(res.msg)
        payClose()
        doRefresh()
      }
    })
  }

  const resetSeach = () => {
    seachRef.value.resetFields()
    doRefresh(1)
  }

  function doRefresh(value?: number) {
    tables.tableLoading = true
    if (value) {
    }
    get({
      url: bpsList,
      data: {
        ...seachForm,
      },
    }).then((res: any) => {
      tables.tableLoading = false
      table.handleSuccess(res.data)
    })
  }

  const seriess = () => {
    useCommon.seriess().then((res) => {
      merchantTypeList.value = res.data
    })
  }

  function onUpdateBorder(isBordered: boolean) {
    tables.bordered = isBordered
  }

  function onUpdateStriped(isStriped: boolean) {
    tables.striped = isStriped
  }

  //跟踪API开始时间限制结束时间
  function changeTraceEnd(time: any) {
    return time.getTime() > new Date(seachForm.endTime).getTime() //大于结束时间的不选
  }
  //跟踪API结束时间限制开始时间
  function changeTraceStart(time: any) {
    return time.getTime() < new Date(seachForm.addTime).getTime() //小于开始时间的不选
  }

  const channel: any = ref([])

  function getchannel() {
    useCommon.channels().then((res: any) => {
      channel.value = res.data
    })
  }

  const mealList: any = ref([])

  function mealListFns() {
    useCommon.mealListFn().then((res: any) => {
      mealList.value = res.data
    })
  }

  onMounted(async () => {
    await doRefresh()
    await getchannel()
    await mealListFns()
    await seriess()
  })
</script>

<style lang="less" scoped>
  :deep(.arco-tabs-nav-extra) {
    margin-right: 20px;
  }
  :deep(.arco-table-cell-expand-icon) {
    justify-content: center;
  }

  :deep(.arco-tabs-nav-tab) {
    background-color: var(--color-bg-1);
    padding: 20px 0;
    border-radius: 10px;
  }

  :deep(.arco-tabs-content::before) {
    height: 0px !important;
  }

  :deep(.arco-tabs-tab) {
    margin: 0 20px;
    padding: 0;
    padding-bottom: 5px;
  }

  :deep(.arco-tabs-nav::before) {
    position: static !important;
    height: 0px !important;
  }

  :deep(.arco-tabs-content) {
    padding: 0;
  }

  .title {
    margin-bottom: 20px;
    background-color: var(--color-bg-1);
    border-radius: 10px;
  }

  .box {
    overflow: hidden; //超出的文本隐藏
    text-overflow: ellipsis; //用省略号显示
    white-space: nowrap;
  }

  .tabs {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 40px;
    margin-bottom: 20px;

    .button {
      box-sizing: border-box;
      padding-bottom: 5px;
      cursor: pointer;
    }
  }

  .action {
    color: #009dff;
    border-bottom: 3px solid #009dff;
  }

  .butten {
    margin-right: 5px;
    padding: 0px;
  }
</style>
